package com.ioftv.controller;

import com.ioftv.common.Result;
import com.ioftv.entity.SupplierRegistration;
import com.ioftv.service.SupplierRegistrationService;
import com.ioftv.dto.PageQuery;
import com.ioftv.dto.PageResult;
import com.ioftv.util.UserContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/admin/supplier-registration")
public class SupplierRegistrationController {
    
    private static final Logger logger = LoggerFactory.getLogger(SupplierRegistrationController.class);
    
    @Autowired
    private SupplierRegistrationService supplierRegistrationService;
    
    /**
     * 提交报名信息
     * @param supplierRegistration 供应商报名信息
     * @return 保存结果
     */
    @PostMapping("/submitRegistration")
    public Result<SupplierRegistration> submitRegistration(@RequestBody SupplierRegistration supplierRegistration, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        try {
            // 设置默认审批状态为未审批
            if (supplierRegistration.getApprovalStatus() == null) {
                supplierRegistration.setApprovalStatus("0");
            }
            SupplierRegistration saved = supplierRegistrationService.saveSupplierRegistration(supplierRegistration);
            return Result.success("报名信息提交成功", saved);
        } catch (Exception e) {
            logger.error("提交报名信息时发生错误: ", e);
            return Result.error("提交报名信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询报名信息列表
     * @param pageQuery 分页参数
     * @param supplierName 供应商名称（模糊查询）
     * @param project 项目名称（模糊查询）
     * @param expertiseType 擅长标注类型（精确查询）
     * @param approvalStatus 审批状态（0-未审批，1-审批通过，2-审批失败）
     * @return 分页结果
     */
    @GetMapping("/getRegistrationList")
    public Result<PageResult<SupplierRegistration>> getRegistrationList(
            PageQuery pageQuery,
            @RequestParam(required = false) String supplierName,
            @RequestParam(required = false) String project,
            @RequestParam(required = false) String expertiseType,
            @RequestParam(required = false) String approvalStatus,
            HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        try {
            PageResult<SupplierRegistration> pageResult = supplierRegistrationService.getSupplierRegistrationList(
                pageQuery, supplierName, project, expertiseType, approvalStatus);
            return Result.success("查询成功", pageResult);
        } catch (Exception e) {
            logger.error("查询报名信息列表时发生错误: ", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询报名信息
     * @param id 报名信息ID
     * @return 报名信息
     */
    @GetMapping("/select/{id}")
    public Result<SupplierRegistration> getRegistrationById(@PathVariable Long id, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        try {
            SupplierRegistration supplierRegistration = supplierRegistrationService.getSupplierRegistrationById(id);
            if (supplierRegistration == null) {
                return Result.error("未找到对应的报名信息");
            }
            return Result.success("查询成功", supplierRegistration);
        } catch (Exception e) {
            logger.error("根据ID查询报名信息时发生错误: ", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 修改报名信息
     * @param id 报名信息ID
     * @param supplierRegistration 更新的报名信息
     * @return 更新结果
     */
    @PostMapping("/update/{id}")
    public Result<SupplierRegistration> updateRegistration(@PathVariable Long id, @RequestBody SupplierRegistration supplierRegistration, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        try {
            // 检查ID是否存在
            SupplierRegistration existing = supplierRegistrationService.getSupplierRegistrationById(id);
            if (existing == null) {
                return Result.error("未找到对应的报名信息");
            }
            
            // 设置ID
            supplierRegistration.setId(id);
            SupplierRegistration updated = supplierRegistrationService.updateSupplierRegistration(supplierRegistration);
            return Result.success("报名信息更新成功", updated);
        } catch (Exception e) {
            logger.error("更新报名信息时发生错误: ", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除报名信息
     * @param id 报名信息ID
     * @return 删除结果
     */
    @PostMapping("/delete/{id}")
    public Result<Void> deleteRegistration(@PathVariable Long id, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        try {
            SupplierRegistration existing = supplierRegistrationService.getSupplierRegistrationById(id);
            if (existing == null) {
                return Result.error("未找到对应的报名信息");
            }
            
            boolean deleted = supplierRegistrationService.deleteSupplierRegistrationById(id);
            if (deleted) {
                return Result.success("报名信息删除成功", null);
            } else {
                return Result.error("报名信息删除失败");
            }
        } catch (Exception e) {
            logger.error("删除报名信息时发生错误: ", e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }
}